<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医院管理系统 - 医生首页</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            min-height: 100vh;
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            padding: 2rem;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .stat-card {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }
        .stat-card .card-body {
            padding: 2rem;
        }
        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
        }
        .table {
            border-radius: 10px;
            overflow: hidden;
        }
        .btn-action {
            padding: 5px 10px;
            margin: 2px;
            border-radius: 5px;
        }
        .modal-content {
            border-radius: 15px;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .patient-info {
            background: #e8f5e8;
            border-left: 4px solid #28a745;
            padding: 1rem;
            margin: 1rem 0;
            border-radius: 0 8px 8px 0;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="p-3">
                    <h4 class="text-center mb-4">
                        <i class="fas fa-user-md me-2"></i>医生工作台
                    </h4>
                    <nav class="nav flex-column">
                        <a class="nav-link active" href="#" onclick="showDashboard()">
                            <i class="fas fa-tachometer-alt me-2"></i>工作台
                        </a>
                        <a class="nav-link" href="#" onclick="showSchedule()">
                            <i class="fas fa-calendar-alt me-2"></i>我的排班
                        </a>
                        <a class="nav-link" href="#" onclick="showReservations()">
                            <i class="fas fa-calendar-check me-2"></i>今日预约
                        </a>
                        <a class="nav-link" href="#" onclick="showMedicalRecordManagement()">
                            <i class="fas fa-file-medical me-2"></i>病历管理
                        </a>
                        <a class="nav-link" href="#" onclick="showHospitalizationApproval()">
                            <i class="fas fa-bed me-2"></i>住院审核
                        </a>
                        <a class="nav-link" href="#" onclick="showDrugPurchaseApproval()">
                            <i class="fas fa-pills me-2"></i>购药审批
                        </a>
                        <a class="nav-link" href="#" onclick="showOrderManagement()">
                            <i class="fas fa-receipt me-2"></i>订单管理
                        </a>
                        <a class="nav-link" href="#" onclick="showProfile()">
                            <i class="fas fa-user me-2"></i>个人信息
                        </a>
                        <hr>
                        <a class="nav-link" href="#" onclick="logout()">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a>
                    </nav>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- 工作台 -->
                <div id="dashboard" class="content-section">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-tachometer-alt me-2"></i>医生工作台</h2>
                        <span class="text-muted" id="doctorName">欢迎回来，医生</span>
                    </div>

                    <!-- 统计卡片 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-check fa-2x mb-2"></i>
                                    <div class="stat-number" id="todayReservations">-</div>
                                    <div>今日预约</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-file-medical fa-2x mb-2"></i>
                                    <div class="stat-number" id="todayRecords">-</div>
                                    <div>今日病历</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-clock fa-2x mb-2"></i>
                                    <div class="stat-number" id="waitingPatients">-</div>
                                    <div>待诊患者</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar fa-2x mb-2"></i>
                                    <div class="stat-number" id="thisWeekReservations">-</div>
                                    <div>本周预约</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 今日预约列表 -->
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-calendar-check me-2"></i>今日预约患者</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>预约时间</th>
                                                    <th>患者姓名</th>
                                                    <th>预约号</th>
                                                    <th>状态</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody id="todayReservationsTable">
                                                <tr>
                                                    <td colspan="5" class="text-center text-muted">暂无今日预约</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-bell me-2"></i>工作提醒</h5>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info">
                                        <small><i class="fas fa-info-circle me-2"></i>您有3个患者等待就诊</small>
                                    </div>
                                    <div class="alert alert-warning">
                                        <small><i class="fas fa-exclamation-triangle me-2"></i>请及时完成病历记录</small>
                                    </div>
                                    <div class="alert alert-success">
                                        <small><i class="fas fa-check-circle me-2"></i>今日工作进展顺利</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 我的排班 -->
                <div id="schedule" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-alt me-2"></i>我的排班</h2>
                        <div class="d-flex gap-2">
                            <input type="date" class="form-control" id="scheduleDate" style="width: auto;">
                            <button class="btn btn-outline-primary" onclick="loadSchedule()">
                                <i class="fas fa-search me-2"></i>查询
                            </button>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>日期</th>
                                            <th>时段</th>
                                            <th>科室</th>
                                            <th>剩余号源</th>
                                            <th>已预约</th>
                                            <th>状态</th>
                                        </tr>
                                    </thead>
                                    <tbody id="scheduleTableBody">
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">暂无排班信息</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 今日预约 -->
                <div id="reservations" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-check me-2"></i>今日预约</h2>
                        <div class="d-flex gap-2">
                            <select class="form-select" id="reservationStatus" style="width: auto;">
                                <option value="">全部状态</option>
                                <option value="1">已预约</option>
                                <option value="2">已就诊</option>
                                <option value="3">已取消</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadReservations()">
                                <i class="fas fa-search me-2"></i>筛选
                            </button>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>预约时间</th>
                                            <th>患者姓名</th>
                                            <th>预约号</th>
                                            <th>联系电话</th>
                                            <th>预约备注</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="reservationsTableBody">
                                        <tr>
                                            <td colspan="7" class="text-center text-muted">暂无预约信息</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                
                <!-- 病历管理 -->
                <div id="medicalRecordManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-file-medical me-2"></i>病历管理</h2>
                        <div class="btn-group">
                            <button class="btn btn-outline-success" onclick="refreshMedicalRecordData()" title="刷新数据">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button class="btn btn-outline-info" onclick="showMedicalRecordStatistics()" title="查看统计">
                                <i class="fas fa-chart-bar"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="exportMedicalRecordData()" title="导出数据">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>

                    <!-- 搜索和筛选 -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                                        <input type="text" class="form-control" id="medicalRecordSearch" placeholder="搜索患者姓名..." onkeyup="filterMedicalRecords()">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="medicalRecordDoctorFilter" onchange="filterMedicalRecords()">
                                        <option value="">所有医生</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <select class="form-select" id="medicalRecordDepartmentFilter" onchange="filterMedicalRecords()">
                                        <option value="">所有科室</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input type="date" class="form-control" id="medicalRecordDateFilter" onchange="filterMedicalRecords()" placeholder="选择日期">
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-outline-secondary" onclick="resetMedicalRecordFilter()">
                                        <i class="fas fa-undo me-1"></i>重置筛选
                                    </button>
                                    <button class="btn btn-outline-primary" onclick="loadMedicalRecords()">
                                        <i class="fas fa-sync-alt me-1"></i>刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>病历ID</th>
                                            <th>预约ID</th>
                                            <th>患者</th>
                                            <th>医生</th>
                                            <th>科室</th>
                                            <th>诊断结果</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="medicalRecordTableBody">
                                        <!-- 动态加载数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 住院审核 -->
                <div id="hospitalizationApproval" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-bed me-2"></i>住院审核</h2>
                        <div class="d-flex gap-2">
                            <select class="form-select" id="approvalStatusFilter" style="width: auto;">
                                <option value="">全部状态</option>
                                <option value="0">待审批</option>
                                <option value="1">已批准</option>
                                <option value="2">已拒绝</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadHospitalizationApplications()">
                                <i class="fas fa-search me-2"></i>筛选
                            </button>
                        </div>
                    </div>

                    <!-- 待审批申请统计 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-clock fa-2x mb-2"></i>
                                    <div class="stat-number" id="pendingApplications">-</div>
                                    <div>待审批</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-check-circle fa-2x mb-2"></i>
                                    <div class="stat-number" id="approvedApplications">-</div>
                                    <div>已批准</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-times-circle fa-2x mb-2"></i>
                                    <div class="stat-number" id="rejectedApplications">-</div>
                                    <div>已拒绝</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                                    <div class="stat-number" id="urgentApplications">-</div>
                                    <div>紧急申请</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 住院申请列表 -->
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-list me-2"></i>住院申请列表</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请编号</th>
                                            <th>患者姓名</th>
                                            <th>申请科室</th>
                                            <th>病房类型</th>
                                            <th>紧急程度</th>
                                            <th>申请时间</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="hospitalizationApplicationsTable">
                                        <tr>
                                            <td colspan="8" class="text-center text-muted">暂无住院申请</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 购药审批 -->
                <div id="drugPurchaseApproval" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-pills me-2"></i>购药审批</h2>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary" onclick="loadDrugPurchasePending()">
                                <i class="fas fa-sync-alt me-2"></i>刷新
                            </button>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>待审批清单</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请编号</th>
                                            <th>患者</th>
                                            <th>申请时间</th>
                                            <th>总金额</th>
                                            <th>明细</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="purchaseApprovalTable">
                                        <tr><td colspan="6" class="text-center text-muted">暂无待审批申请</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 订单管理 -->
                <div id="orderManagement" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-receipt me-2"></i>订单管理</h2>
                        <div class="d-flex gap-2">
                            <select class="form-select" id="orderStatusFilter" style="width:auto;">
                                <option value="">全部</option>
                                <option value="0">未支付</option>
                                <option value="1">已支付</option>
                                <option value="2">已退款</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadAllOrders()">
                                <i class="fas fa-sync-alt me-2"></i>刷新
                            </button>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>订单号</th>
                                            <th>患者ID</th>
                                            <th>项目</th>
                                            <th>金额</th>
                                            <th>支付状态</th>
                                            <th>来源</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="ordersTableBody">
                                        <tr><td colspan="8" class="text-center text-muted">暂无订单</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 个人信息 -->
                <div id="profile" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-user me-2"></i>个人信息</h2>
                        <button class="btn btn-outline-primary" onclick="editProfile()">
                            <i class="fas fa-edit me-2"></i>编辑信息
                        </button>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-body">
                                    <form id="profileForm">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">医生ID</label>
                                                <input type="text" class="form-control" id="profileDId" readonly>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">姓名</label>
                                                <input type="text" class="form-control" id="profileName" readonly>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">性别</label>
                                                <input type="text" class="form-control" id="profileSex" readonly>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">年龄</label>
                                                <input type="text" class="form-control" id="profileAge" readonly>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">职称</label>
                                                <input type="text" class="form-control" id="profileTitle" readonly>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">专业</label>
                                                <input type="text" class="form-control" id="profileMajor" readonly>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">医生简介</label>
                                            <textarea class="form-control" id="profileInfo" rows="3" readonly></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">所属科室</label>
                                            <input type="text" class="form-control" id="profileDepName" readonly>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5>工作统计</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <small class="text-muted">本月接诊患者</small>
                                        <div class="h4 text-primary" id="monthlyPatients">0</div>
                                    </div>
                                    <div class="mb-3">
                                        <small class="text-muted">本月病历记录</small>
                                        <div class="h4 text-success" id="monthlyRecords">0</div>
                                    </div>
                                    <div class="mb-3">
                                        <small class="text-muted">工作满意度</small>
                                        <div class="h4 text-warning" id="satisfaction">98%</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>




    <!-- 新建病历模态框 -->
    <div class="modal fade" id="addRecordModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新建病历</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addRecordForm">
                        <div class="mb-3">
                            <label class="form-label">预约</label>
                            <div id="recordPatientInfo" class="form-text">将自动关联当前预约</div>
                        </div>
                        <div class="mb-3">
                            <label for="recordResult" class="form-label">诊断结果 *</label>
                            <input type="text" class="form-control" id="recordResult" name="result" required>
                        </div>
                        <div class="mb-3">
                            <label for="recordInfo" class="form-label">病情描述 *</label>
                            <textarea class="form-control" id="recordInfo" name="info" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="recordAdvice" class="form-label">医嘱 *</label>
                            <textarea class="form-control" id="recordAdvice" name="advice" rows="4" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addRecord()">保存病历</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 患者详情模态框 -->
    <div class="modal fade" id="patientDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">患者详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="patientDetailContent">
                    <!-- 动态加载患者详情 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="startDiagnosis()">开始诊断</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 住院申请详情模态框 -->
    <div class="modal fade" id="admissionDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">住院申请详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="admissionDetailContent">
                    <!-- 动态加载申请详情 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-success" id="approveBtn" onclick="approveApplication()">批准申请</button>
                    <button type="button" class="btn btn-danger" id="rejectBtn" onclick="showRejectModal()">拒绝申请</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 拒绝申请模态框 -->
    <div class="modal fade" id="rejectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">拒绝住院申请</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="rejectReason" class="form-label">拒绝原因 *</label>
                        <textarea class="form-control" id="rejectReason" rows="4" required 
                                  placeholder="请详细说明拒绝住院申请的原因"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmRejectApplication()">确认拒绝</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/axios.min.js"></script>
    <script>
        // 配置axios
        axios.defaults.baseURL = '';
        
        // 添加请求拦截器
        axios.interceptors.request.use(function (config) {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            }
            return config;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(
            function (response) {
                return response;
            },
            function (error) {
                if (error.response && error.response.status === 401) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    window.location.href = '/login';
                }
                return Promise.reject(error);
            }
        );

        // 通用 API 调用助手
        async function apiCall(url, options = {}) {
            try {
                const method = options.method || 'get';
                const response = await axios({
                    url,
                    method,
                    params: options.params,
                    data: options.data,
                    headers: options.headers || {}
                });

                // 兼容后端统一返回结构 Result { code, msg, data }
                if (response && response.data && response.data.code === 200) {
                    return { success: true, data: response.data };
                }

                // 退化处理：HTTP 200 但业务码非 200
                return {
                    success: false,
                    error: (response && response.data && (response.data.msg || response.data.message)) || '请求失败',
                    data: response?.data
                };
            } catch (error) {
                const message =
                    (error.response && (error.response.data?.msg || error.response.data?.message)) ||
                    error.message ||
                    '网络错误';
                return { success: false, error: message };
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadUserInfo();
            loadDashboardData();
        });

        // 加载用户信息
        function loadUserInfo() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            if (userInfo.uName) {
                document.getElementById('doctorName').textContent = `欢迎回来，${userInfo.uName}`;
            }
        }

        // 显示工作台
        function showDashboard() {
            hideAllSections();
            document.getElementById('dashboard').style.display = 'block';
            updateActiveNav('dashboard');
            loadDashboardData();
        }

        // 显示排班
        function showSchedule() {
            hideAllSections();
            document.getElementById('schedule').style.display = 'block';
            updateActiveNav('schedule');
            loadSchedule();
        }

        // 显示预约
        function showReservations() {
            hideAllSections();
            document.getElementById('reservations').style.display = 'block';
            updateActiveNav('reservations');
            loadReservations();
        }

        // // 显示病历管理
        // function showMedicalRecords() {
        //     hideAllSections();
        //     document.getElementById('medicalRecords').style.display = 'block';
        //     updateActiveNav('medicalRecords');
        //     loadMedicalRecords();
        // }

        // 显示住院审核
        function showHospitalizationApproval() {
            hideAllSections();
            document.getElementById('hospitalizationApproval').style.display = 'block';
            updateActiveNav('hospitalizationApproval');
            loadHospitalizationApplications();
        }

        // 显示订单管理
        function showOrderManagement(){
            hideAllSections();
            document.getElementById('orderManagement').style.display = 'block';
            updateActiveNav('orderManagement');
            loadAllOrders();
        }

        async function loadAllOrders(){
            const tbody = document.getElementById('ordersTableBody');
            const status = document.getElementById('orderStatusFilter')?.value || '';
            try{
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载中...</td></tr>';
                const url = status === '' ? '/orders/all' : `/orders/all?status=${status}`;
                const res = await axios.get(url);
                if (!(res.data && res.data.code === 200)){
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const list = res.data.data || [];
                if (!list.length){
                    tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无订单</td></tr>';
                    return;
                }
                const badge = s => s===1? 'bg-success' : (s===2? 'bg-secondary' : 'bg-warning');
                const text = s => s===1? '已支付' : (s===2? '已退款' : '未支付');
                const srcText = t => t===1? '住院押金' : (t===2? '购药' : '-');
                tbody.innerHTML = list.map(o => {
                    const time = o.createTime ? new Date(o.createTime).toLocaleString() : '-';
                    const amt = (Number(o.amount)||0).toFixed(2);
                    const canRefund = o.payStatus === 1;
                    return `<tr>
                        <td>OD${o.orderId}</td>
                        <td>${o.pid}</td>
                        <td>${o.item}</td>
                        <td>${amt}</td>
                        <td><span class="badge ${badge(o.payStatus)}">${text(o.payStatus)}</span></td>
                        <td>${srcText(o.sourceType)}</td>
                        <td>${time}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-danger" ${canRefund? '' : 'disabled'} onclick="refundOrder(${o.orderId})">退款</button>
                        </td>
                    </tr>`;
                }).join('');
            } catch(e){
                console.error('加载订单失败', e);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        async function refundOrder(orderId){
            if(!confirm('确认对该订单执行退款吗？')) return;
            try{
                const res = await axios.post(`/orders/refund/${orderId}`);
                if (res.data && res.data.code === 200){
                    alert('退款成功');
                    loadAllOrders();
                } else {
                    alert('退款失败：' + (res.data?.msg || '未知错误'));
                }
            }catch(e){
                console.error('退款失败', e);
                alert('退款失败，请稍后重试');
            }
        }

        // 显示个人信息
        function showProfile() {
            hideAllSections();
            document.getElementById('profile').style.display = 'block';
            updateActiveNav('profile');
            console.log('显示个人信息模块');
            loadProfile();
        }

        // 隐藏所有内容区域
        function hideAllSections() {
            const sections = document.querySelectorAll('.content-section');
            sections.forEach(section => {
                section.style.display = 'none';
            });
        }

        // 更新活跃导航
        function updateActiveNav(activeId) {
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.classList.remove('active');
            });
            
            // 根据activeId设置对应的导航为活跃状态
            const navMap = {
                'dashboard': 0,
                'schedule': 1, 
                'reservations': 2,
                'medicalRecords': 3,
                'profile': 4
            };
            
            const activeIndex = navMap[activeId];
            if (activeIndex !== undefined && navLinks[activeIndex]) {
                navLinks[activeIndex].classList.add('active');
            }
        }

        // 加载工作台数据
        async function loadDashboardData() {
            try {
                // 模拟数据
                document.getElementById('todayReservations').textContent = '8';
                document.getElementById('todayRecords').textContent = '5';
                document.getElementById('waitingPatients').textContent = '3';
                document.getElementById('thisWeekReservations').textContent = '45';
                
                // 加载今日预约
                loadTodayReservations();
            } catch (error) {
                console.error('加载工作台数据失败:', error);
            }
        }

        // 工具：获取医生ID
        function getDoctorIdFromStorage() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            return userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
        }

        // 工具：状态徽章
        function renderReservationBadge(rState) {
            if (rState === 1) return '<span class="badge bg-success">已就诊</span>';
            if (rState === 2) return '<span class="badge bg-secondary">已取消</span>';
            return '<span class="badge bg-warning">待就诊</span>';
        }

        // 工具：映射筛选
        function mapFilterToRState(value) {
            if (value === '1') return 0;
            if (value === '2') return 1;
            if (value === '3') return 2;
            return undefined;
        }

        async function parallelAll(tasks) {
            return Promise.all(tasks.map(t => t().catch(e => ({ __error: e }))));
        }

        // 最近一次加载的预约列表（供查看详情使用）
        let latestReservationsForView = [];
        // 诊断弹窗当前选中的预约ID
        let currentDiagnosisReservationId = null;

        // 加载今日预约（工作台小表）
        async function loadTodayReservations() {
                const tbody = document.getElementById('todayReservationsTable');
            showLoadingState('todayReservationsTable', '正在加载今日预约...', 5);
            try {
                let dId = getDoctorIdFromStorage();
                if (!dId) {
                    try {
                        const resp = await axios.get('/doctor/query');
                        if (resp.data?.code === 200 && Array.isArray(resp.data.data) && resp.data.data.length > 0) {
                            dId = resp.data.data[0].did;
                        }
                    } catch (e) {}
                }
                if (!dId) {
                    showErrorState('todayReservationsTable', '无法获取医生ID', 5);
                    return;
                }

                const today = new Date();
                const yyyy = today.getFullYear();
                const mm = String(today.getMonth() + 1).padStart(2, '0');
                const dd = String(today.getDate()).padStart(2, '0');
                const dateStr = `${yyyy}-${mm}-${dd}`;

                const scheduleRes = await apiCall('/schedule/time', { params: { DId: dId, date: dateStr } });
                if (!scheduleRes.success) {
                    showErrorState('todayReservationsTable', '加载排班失败：' + scheduleRes.error, 5);
                    return;
                }
                const schedules = Array.isArray(scheduleRes.data.data) ? scheduleRes.data.data : [];
                if (schedules.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无今日预约</td></tr>';
                    document.getElementById('todayReservations').textContent = '0';
                    document.getElementById('waitingPatients').textContent = '0';
                    return;
                }

                const reservationResults = await parallelAll(
                    schedules.map(s => async () => {
                        const sid = s.sId || s.sid;
                        if (!sid) return { schedule: s, reservations: [] };
                        const r = await apiCall(`/reservation/query/${sid}`);
                        return { schedule: s, reservations: r.success ? (r.data.data || []) : [] };
                    })
                );

                const allReservations = [];
                reservationResults.forEach(item => {
                    if (item && !item.__error && item.reservations) {
                        item.reservations.forEach(rv => allReservations.push({ schedule: item.schedule, rv }));
                    }
                });

                if (allReservations.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无今日预约</td></tr>';
                    document.getElementById('todayReservations').textContent = '0';
                    document.getElementById('waitingPatients').textContent = '0';
                    return;
                }

                const patientMap = {};
                await parallelAll(
                    allReservations.map(item => async () => {
                        const pId = item.rv.pId || item.rv.pid || item.rv.PId || item.rv.PID;
                        if (!pId || patientMap[pId]) return;
                        const p = await apiCall(`/patient/info/${pId}`);
                        if (p.success) patientMap[pId] = p.data.data || {};
                    })
                );

                // 缓存供详情使用
                latestReservationsForView = allReservations;

                tbody.innerHTML = '';
                let waiting = 0;
                allReservations.forEach(({ schedule, rv }) => {
                    const pid = rv.pId || rv.pid || rv.PId || rv.PID;
                    const patient = patientMap[pid] || {};
                    const displayTime = schedule?.time || '-';
                    const name = patient.pName || patient.pname || '-';
                    const rnum = rv.rNum || rv.rnum || '-';
                    const state = rv.rState ?? rv.rstate;
                    const stateBadge = renderReservationBadge(state);
                    if (state === 0) waiting++;
                    tbody.innerHTML += `
                        <tr>
                            <td>${displayTime}</td>
                            <td>${name}</td>
                            <td>${rnum}</td>
                            <td>${stateBadge}</td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="viewPatient(${pid || 0})">查看</button>
                            </td>
                        </tr>
                    `;
                });

                document.getElementById('todayReservations').textContent = String(allReservations.length);
                document.getElementById('waitingPatients').textContent = String(waiting);
            } catch (error) {
                console.error('加载今日预约失败:', error);
                showErrorState('todayReservationsTable', '加载失败，请稍后重试', 5);
            }
        }

        // 加载排班信息
        async function loadSchedule() {
            try {
                console.log('=== 开始加载排班信息 ===');
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                console.log('用户信息:', userInfo);
                
                // 尝试多种方式获取医生ID
                let dId = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                console.log('从localStorage获取到的医生ID:', dId);
                
                if (!dId) {
                    console.log('从localStorage未找到医生ID，尝试从后端获取...');
                    try {
                        const response = await axios.get('/doctor/query');
                        console.log('获取所有医生响应:', response.data);
                        if (response.data.code === 200 && response.data.data.length > 0) {
                            dId = response.data.data[0].did;
                            console.log('从后端获取到医生ID:', dId);
                        }
                    } catch (e) {
                        console.error('从后端获取医生信息失败:', e);
                    }
                }
                
                if (!dId) {
                    console.error('无法获取医生ID');
                    document.getElementById('scheduleTableBody').innerHTML = 
                        '<tr><td colspan="6" class="text-center text-muted">无法获取医生ID</td></tr>';
                    return;
                }
                
                const date = document.getElementById('scheduleDate').value;
                console.log('查询排班参数 - 医生ID:', dId, '日期:', date);
                
                // 使用新的接口查询医生的所有排班
                let response;
                let schedules = [];
                
                try {
                    console.log('使用 /schedule/all 接口查询医生所有排班');
                    response = await axios.get('/schedule/all', {
                        params: { DId: dId }
                    });
                    console.log('查询医生所有排班结果:', response.data);
                    
                    if (response.data.code === 200) {
                        schedules = response.data.data || [];
                        console.log('获取到排班数据:', schedules);
                    }
                } catch (error1) {
                    console.error('查询医生所有排班失败:', error1);
                    
                    // 备用方案：尝试其他接口
                    try {
                        console.log('尝试备用方案：查询所有排班');
                        response = await axios.get('/schedule/query');
                        console.log('备用方案查询结果:', response.data);
                        if (response.data.code === 200) {
                            // 过滤出当前医生的排班
                            const allSchedules = response.data.data || [];
                            schedules = allSchedules.filter(s => s.dId === dId);
                            console.log('过滤后的排班:', schedules);
                        }
                    } catch (error2) {
                        console.error('备用方案也失败:', error2);
                    }
                }
                
                // 如果指定了日期，过滤出该日期的排班
                if (schedules.length > 0 && date && date !== '') {
                    const targetDate = new Date(date).toISOString().split('T')[0];
                    console.log('目标日期:', targetDate);
                    const filteredSchedules = schedules.filter(schedule => {
                        let scheduleDate = null;
                        if (schedule.date) {
                            if (typeof schedule.date === 'string') {
                                // 处理各种日期格式
                                if (schedule.date.includes('T')) {
                                    scheduleDate = schedule.date.split('T')[0];
                                } else if (schedule.date.includes('-')) {
                                    scheduleDate = schedule.date;
                                } else {
                                    // 尝试解析其他格式
                                    try {
                                        scheduleDate = new Date(schedule.date).toISOString().split('T')[0];
                                    } catch (e) {
                                        scheduleDate = schedule.date;
                                    }
                                }
                            } else if (schedule.date.toISOString) {
                                scheduleDate = schedule.date.toISOString().split('T')[0];
                            }
                        }
                        console.log('排班日期:', scheduleDate, '目标日期:', targetDate, '匹配:', scheduleDate === targetDate);
                        return scheduleDate === targetDate;
                    });
                    console.log('按日期过滤后的排班:', filteredSchedules);
                    schedules = filteredSchedules;
                } else {
                    console.log('不进行日期过滤，显示所有排班');
                }
                
                console.log('最终排班数据:', schedules);
                console.log('排班数量:', schedules ? schedules.length : 0);
                
                const tbody = document.getElementById('scheduleTableBody');
                tbody.innerHTML = '';
                
                if (schedules && schedules.length > 0) {
                    schedules.forEach((schedule, index) => {
                        console.log(`排班 ${index + 1}:`, schedule);
                        
                        // 处理日期显示
                        let displayDate = schedule.date || date;
                        if (displayDate && typeof displayDate === 'string') {
                            try {
                                if (displayDate.includes('T')) {
                                    displayDate = new Date(displayDate).toLocaleDateString();
                                } else if (displayDate.includes('-')) {
                                    displayDate = new Date(displayDate).toLocaleDateString();
                                }
                            } catch (e) {
                                console.warn('日期解析失败:', displayDate, e);
                            }
                        }
                        
                        // 处理时段显示
                        let displayTime = schedule.time || '未设置';
                        
                        // 处理科室显示
                        let displayDep = '科室' + (schedule.depId || '未设置');
                        
                        const row = `
                            <tr>
                                <td>${displayDate}</td>
                                <td>${displayTime}</td>
                                <td>${displayDep}</td>
                                <td>${schedule.remain || 0}</td>
                                <td>${schedule.already || 0}</td>
                                <td><span class="badge bg-success">正常</span></td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                    });
                    console.log('排班信息显示完成');
                } else {
                    console.log('该医生暂无排班信息，显示提示信息');
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">该医生暂无排班信息</td></tr>';
                }
            } catch (error) {
                console.error('加载排班信息失败:', error);
                document.getElementById('scheduleTableBody').innerHTML = 
                    '<tr><td colspan="6" class="text-center text-muted">加载失败，请检查网络连接</td></tr>';
            }
        }

        // 加载预约信息（今日预约页）
        async function loadReservations() {
                const tbody = document.getElementById('reservationsTableBody');
            showLoadingState('reservationsTableBody', '正在加载预约信息...');
            try {
                let dId = getDoctorIdFromStorage();
                if (!dId) {
                    try {
                        const resp = await axios.get('/doctor/query');
                        if (resp.data?.code === 200 && Array.isArray(resp.data.data) && resp.data.data.length > 0) {
                            dId = resp.data.data[0].did;
                        }
                    } catch (e) {}
                }
                if (!dId) {
                    showErrorState('reservationsTableBody', '无法获取医生ID');
                    return;
                }

                const today = new Date();
                const yyyy = today.getFullYear();
                const mm = String(today.getMonth() + 1).padStart(2, '0');
                const dd = String(today.getDate()).padStart(2, '0');
                const dateStr = `${yyyy}-${mm}-${dd}`;

                const scheduleRes = await apiCall('/schedule/time', { params: { DId: dId, date: dateStr } });
                if (!scheduleRes.success) {
                    showErrorState('reservationsTableBody', '加载排班失败：' + scheduleRes.error);
                    return;
                }
                const schedules = Array.isArray(scheduleRes.data.data) ? scheduleRes.data.data : [];
                if (schedules.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无预约信息</td></tr>';
                    return;
                }

                const reservationResults = await parallelAll(
                    schedules.map(s => async () => {
                        const sid = s.sId || s.sid;
                        if (!sid) return { schedule: s, reservations: [] };
                        const r = await apiCall(`/reservation/query/${sid}`);
                        return { schedule: s, reservations: r.success ? (r.data.data || []) : [] };
                    })
                );

                const allReservations = [];
                reservationResults.forEach(item => {
                    if (item && !item.__error && item.reservations) {
                        item.reservations.forEach(rv => allReservations.push({ schedule: item.schedule, rv }));
                    }
                });

                // 状态过滤
                const statusVal = document.getElementById('reservationStatus')?.value || '';
                const targetState = mapFilterToRState(statusVal);
                const filtered = typeof targetState === 'number'
                    ? allReservations.filter(x => x.rv.rState === targetState)
                    : allReservations;

                const patientMap = {};
                await parallelAll(
                    filtered.map(item => async () => {
                        const pId = item.rv.pId || item.rv.pid || item.rv.PId || item.rv.PID;
                        if (!pId || patientMap[pId]) return;
                        const p = await apiCall(`/patient/info/${pId}`);
                        if (p.success) patientMap[pId] = p.data.data || {};
                    })
                );

                if (filtered.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无预约信息</td></tr>';
                    return;
                }

                // 缓存供详情使用
                latestReservationsForView = filtered;

                tbody.innerHTML = '';
                filtered.forEach(({ schedule, rv }) => {
                    const pid = rv.pId || rv.pid || rv.PId || rv.PID;
                    const patient = patientMap[pid] || {};
                    const displayTime = schedule?.time || '-';
                    const name = patient.pName || patient.pname || '-';
                    const phone = patient.pPhone || patient.pphone || '-';
                    const info = rv.rInfo || rv.rinfo || '-';
                    const rnum = rv.rNum || rv.rnum || '-';
                    const state = rv.rState ?? rv.rstate;
                    const stateBadge = renderReservationBadge(state);
                    tbody.innerHTML += `
                        <tr>
                            <td>${displayTime}</td>
                            <td>${name}</td>
                            <td>${rnum}</td>
                            <td>${phone}</td>
                            <td>${info}</td>
                            <td>${stateBadge}</td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="viewPatient(${pid || 0})">查看</button>
                                <button class="btn btn-sm btn-success" onclick="startDiagnosis(${(rv.rId || rv.rid || 0)})">诊断</button>
                        </td>
                    </tr>
                `;
                });
            } catch (error) {
                console.error('加载预约信息失败:', error);
                showErrorState('reservationsTableBody', '加载失败，请稍后重试');
            }
        }
                // 显示加载状态
        function showLoadingState(elementId, message = '加载中...', colspan = 8) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<tr><td colspan="${colspan}" class="text-center">
                    <div class="spinner-border spinner-border-sm me-2"></div>${message}
                </td></tr>`;
            }
        }

        // 显示错误状态
        function showErrorState(elementId, message, colspan = 8) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<tr><td colspan="${colspan}" class="text-center text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>${message}
                </td></tr>`;
            }
        }

        // 显示病历管理
        function showMedicalRecordManagement() {
            hideAllSections();
            document.getElementById('medicalRecordManagement').style.display = 'block';
            updateActiveNav('medicalRecordManagement');
            loadMedicalRecords();
        }

        // 存储原始病历数据
        let allMedicalRecords = [];

        // 加载病历数据
        async function loadMedicalRecords() {
                const tbody = document.getElementById('medicalRecordTableBody');
            
            try {
                // 显示加载状态
                showLoadingState('medicalRecordTableBody', '正在加载病历数据...');
                
                console.log('开始加载病历数据...');
                
                // 优先按当前医生ID获取病历
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const dId = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                let allData = [];
                try {
                    if (dId) {
                        const resp = await axios.get(`/medical/record/doctor/${dId}`);
                        if (resp.data && resp.data.code === 200) {
                            allData = resp.data.data || [];
                        }
                    }
                } catch (e) { /* 忽略，回退到全量接口 */ }
                if (!allData.length) {
                    // 回退：管理员接口（若无权限或空则视为无数据）
                    try {
                        const fallback = await axios.get('/medical/record/queryAll');
                        if (fallback.data && fallback.data.code === 200) {
                            allData = fallback.data.data || [];
                        }
                    } catch (e) { /* ignore */ }
                }
                allMedicalRecords = allData;
                console.log('病历数据:', allMedicalRecords);
                
                // 调试：打印第一条数据的字段
                if (allMedicalRecords.length > 0) {
                    console.log('第一条病历数据的字段:', Object.keys(allMedicalRecords[0]));
                    console.log('第一条病历数据详情:', allMedicalRecords[0]);
                }
                
                // 显示数据
                displayMedicalRecords(allMedicalRecords);
                loadMedicalRecordFilterOptions();
                
                console.log(`成功加载 ${allMedicalRecords.length} 条病历数据`);
                
            } catch (error) {
                console.error('加载病历数据失败:', error);
                showErrorState('medicalRecordTableBody', '加载失败，请检查网络连接');
            }
        }

        // 显示病历数据
        function displayMedicalRecords(medicalRecords) {
            const tbody = document.getElementById('medicalRecordTableBody');
            if (!tbody) {
                console.error('找不到病历表格体元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            if (!medicalRecords || !Array.isArray(medicalRecords) || medicalRecords.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted"><i class="fas fa-info-circle me-2"></i>暂无病历数据</td></tr>';
                return;
            }
            
            try {
                medicalRecords.forEach((record, index) => {
                    // 验证病历数据完整性
                    if (!record || typeof record !== 'object') {
                        console.warn(`病历数据格式错误，索引: ${index}`, record);
                        return;
                    }
                    
                    // 安全地获取病历属性
                    const safeGet = (obj, prop, defaultValue = '-') => {
                        return obj && obj[prop] !== undefined && obj[prop] !== null ? obj[prop] : defaultValue;
                    };
                    
                    // 处理创建时间显示
                    let createTimeStr = '-';
                    if (record.mTime) {
                        try {
                            if (typeof record.mTime === 'string') {
                                createTimeStr = new Date(record.mTime).toLocaleString();
                            } else {
                                createTimeStr = record.mTime.toLocaleString();
                            }
                        } catch (e) {
                            createTimeStr = record.mTime.toString();
                        }
                    }
                    
                    // 处理诊断结果显示（截取前50个字符）
                    let resultText = safeGet(record, 'mResult');
                    if (resultText && resultText.length > 50) {
                        resultText = resultText.substring(0, 50) + '...';
                    }
                    
                    const row = `
                        <tr data-medical-record-id="${safeGet(record, 'mId', '')}">
                            <td>${safeGet(record, 'mId')}</td>
                            <td>${safeGet(record, 'reservationId') || safeGet(record, 'rId')}</td>
                            <td>${safeGet(record, 'pname')}</td>
                            <td>${safeGet(record, 'dname')}</td>
                            <td>${safeGet(record, 'depName')}</td>
                            <td title="${safeGet(record, 'mResult')}">${resultText}</td>
                            <td>${createTimeStr}</td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-info btn-action" 
                                            onclick="viewMedicalRecordDetail(${safeGet(record, 'mId', 0)})" 
                                            title="查看详情"
                                            ${!record.mId ? 'disabled' : ''}>
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary btn-action" 
                                            onclick="editMedicalRecord(${safeGet(record, 'mId', 0)})" 
                                            title="编辑病历"
                                            ${!record.mId ? 'disabled' : ''}>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
                
                console.log(`成功显示 ${medicalRecords.length} 条病历数据`);
            } catch (error) {
                console.error('显示病历数据时发生错误:', error);
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger"><i class="fas fa-exclamation-triangle me-2"></i>显示数据时发生错误</td></tr>';
            }
        }

        // 加载病历筛选选项
        function loadMedicalRecordFilterOptions() {
            // 加载医生筛选选项
            const doctorSelect = document.getElementById('medicalRecordDoctorFilter');
            if (doctorSelect) {
                doctorSelect.innerHTML = '<option value="">所有医生</option>';
                const doctors = [...new Set(allMedicalRecords.map(r => r.dname).filter(Boolean))];
                doctors.forEach(doctor => {
                    const option = document.createElement('option');
                    option.value = doctor;
                    option.textContent = doctor;
                    doctorSelect.appendChild(option);
                });
            }
            
            // 加载科室筛选选项
            const departmentSelect = document.getElementById('medicalRecordDepartmentFilter');
            if (departmentSelect) {
                departmentSelect.innerHTML = '<option value="">所有科室</option>';
                const departments = [...new Set(allMedicalRecords.map(r => r.depName).filter(Boolean))];
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept;
                    option.textContent = dept;
                    departmentSelect.appendChild(option);
                });
            }
        }

        // 筛选病历
        function filterMedicalRecords() {
            try {
                const searchTerm = document.getElementById('medicalRecordSearch')?.value?.toLowerCase() || '';
                const doctorFilter = document.getElementById('medicalRecordDoctorFilter')?.value || '';
                const departmentFilter = document.getElementById('medicalRecordDepartmentFilter')?.value || '';
                const dateFilter = document.getElementById('medicalRecordDateFilter')?.value || '';
                
                if (!allMedicalRecords || !Array.isArray(allMedicalRecords)) {
                    console.warn('病历数据未加载或格式错误');
                    displayMedicalRecords([]);
                    return;
                }
                
                const filteredRecords = allMedicalRecords.filter(record => {
                    if (!record || typeof record !== 'object') return false;
                    
                    // 患者姓名匹配
                    const nameMatch = !searchTerm || 
                        (record.pname && record.pname.toLowerCase().includes(searchTerm));
                    
                    // 医生匹配
                    const doctorMatch = !doctorFilter || 
                        (record.dname && record.dname === doctorFilter);
                    
                    // 科室匹配
                    const departmentMatch = !departmentFilter || 
                        (record.depName && record.depName === departmentFilter);
                    
                    // 日期匹配
                    let dateMatch = true;
                    if (dateFilter) {
                        try {
                            let recordDateStr = '';
                            if (record.mTime) {
                                if (typeof record.mTime === 'string') {
                                    recordDateStr = new Date(record.mTime).toISOString().split('T')[0];
                                } else {
                                    recordDateStr = record.mTime.toISOString().split('T')[0];
                                }
                            }
                            dateMatch = recordDateStr === dateFilter;
                        } catch (e) {
                            dateMatch = false;
                        }
                    }
                    
                    return nameMatch && doctorMatch && departmentMatch && dateMatch;
                });
                
                displayMedicalRecords(filteredRecords);
                console.log(`筛选结果: ${filteredRecords.length}/${allMedicalRecords.length} 条病历`);
                
            } catch (error) {
                console.error('筛选病历时发生错误:', error);
                displayMedicalRecords([]);
            }
        }

        // 重置病历筛选
        function resetMedicalRecordFilter() {
            try {
                const searchInput = document.getElementById('medicalRecordSearch');
                const doctorSelect = document.getElementById('medicalRecordDoctorFilter');
                const departmentSelect = document.getElementById('medicalRecordDepartmentFilter');
                const dateInput = document.getElementById('medicalRecordDateFilter');
                
                if (searchInput) searchInput.value = '';
                if (doctorSelect) doctorSelect.value = '';
                if (departmentSelect) departmentSelect.value = '';
                if (dateInput) dateInput.value = '';
                
                displayMedicalRecords(allMedicalRecords);
                console.log('病历筛选已重置');
            } catch (error) {
                console.error('重置筛选时发生错误:', error);
            }
        }

        // 刷新病历数据
        async function refreshMedicalRecordData() {
            console.log('手动刷新病历数据...');
            await loadMedicalRecords();
        }

        // 查看病历详情
        async function viewMedicalRecordDetail(mId) {
            try {
                if (!mId || mId <= 0) {
                    alert('无效的病历ID');
                    return;
                }
                
                // 从已加载的数据中查找病历
                const record = allMedicalRecords.find(r => r.mId === mId);
                if (!record) {
                    alert('病历信息不存在');
                    return;
                }
                
                // 显示病历详情
                const message = `
病历详情：
病历ID：${record.mId}
预约ID：${record.reservationId || record.rId}
患者：${record.pname || '-'}
医生：${record.dname || '-'}
科室：${record.depName || '-'}
创建时间：${record.mTime || '-'}

诊断结果：
${record.mResult || '无'}

病历信息：
${record.mInfo || '无'}

医嘱建议：
${record.mAdvice || '无'}
                `;
                alert(message);
                
            } catch (error) {
                console.error('查看病历详情失败:', error);
                alert('查看病历详情失败，请检查网络连接');
            }
        }

        // 编辑病历
        async function editMedicalRecord(mId) {
            try {
                if (!mId || mId <= 0) {
                    alert('无效的病历ID');
                    return;
                }
                
                // 从已加载的数据中查找病历
                const record = allMedicalRecords.find(r => r.mId === mId);
                if (!record) {
                    alert('病历信息不存在');
                    return;
                }
                
                // 显示编辑提示
                alert('病历编辑功能需要医生权限，请联系相关医生进行修改。\n\n病历ID：' + mId);
                
            } catch (error) {
                console.error('编辑病历失败:', error);
                alert('编辑病历失败，请检查网络连接');
            }
        }

        // 导出病历数据
        function exportMedicalRecordData() {
            try {
                if (!allMedicalRecords || allMedicalRecords.length === 0) {
                    alert('没有病历数据可导出');
                    return;
                }
                
                const headers = ['病历ID', '预约ID', '患者', '医生', '科室', '诊断结果', '创建时间'];
                const csvContent = [
                    headers.join(','),
                    ...allMedicalRecords.map(record => [
                        record.mId || '',
                        record.reservationId || record.rId || '',
                        record.pname || '',
                        record.dname || '',
                        record.depName || '',
                        (record.mResult || '').replace(/,/g, ';'), // 替换逗号避免CSV格式问题
                        record.mTime || ''
                    ].join(','))
                ].join('\n');
                
                const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `病历数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                console.log('病历数据导出成功');
            } catch (error) {
                console.error('导出病历数据失败:', error);
                alert('导出失败，请重试');
            }
        }

        // 显示病历统计信息
        function showMedicalRecordStatistics() {
            if (!allMedicalRecords || allMedicalRecords.length === 0) {
                alert('暂无病历数据');
                return;
            }
            
            const stats = {
                total: allMedicalRecords.length,
                byDepartment: {},
                byDoctor: {},
                recentCount: 0
            };
            
            // 计算最近7天的病历数量
            const sevenDaysAgo = new Date();
            sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
            
            allMedicalRecords.forEach(record => {
                // 按科室统计
                const depName = record.depName || '未知科室';
                if (!stats.byDepartment[depName]) {
                    stats.byDepartment[depName] = 0;
                }
                stats.byDepartment[depName]++;
                
                // 按医生统计
                const doctorName = record.dname || '未知医生';
                if (!stats.byDoctor[doctorName]) {
                    stats.byDoctor[doctorName] = 0;
                }
                stats.byDoctor[doctorName]++;
                
                // 最近7天统计
                if (record.mTime) {
                    try {
                        const recordDate = new Date(record.mTime);
                        if (recordDate >= sevenDaysAgo) {
                            stats.recentCount++;
                        }
                    } catch (e) {
                        // 忽略日期解析错误
                    }
                }
            });
            
            const message = `
病历统计信息：
总病历数：${stats.total}
最近7天：${stats.recentCount}

各科室分布：
${Object.entries(stats.byDepartment)
    .map(([dep, count]) => `${dep}：${count}份`)
    .join('\n')}

医生工作量：
${Object.entries(stats.byDoctor)
    .map(([doctor, count]) => `${doctor}：${count}份`)
    .join('\n')}
            `;
            alert(message);
        }

        // 加载个人信息
        async function loadProfile() {
            try {
                console.log('开始加载个人信息...');
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                console.log('用户信息:', userInfo);
                
                // 尝试多种方式获取医生ID
                let dId = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                console.log('从localStorage获取到的医生ID:', dId);
                
                if (!dId) {
                    console.log('从localStorage未找到医生ID，尝试从后端获取...');
                    try {
                        const response = await axios.get('/doctor/query');
                        console.log('获取所有医生响应:', response.data);
                        if (response.data.code === 200 && response.data.data.length > 0) {
                            dId = response.data.data[0].did;
                            console.log('从后端获取到医生ID:', dId);
                        }
                    } catch (e) {
                        console.error('从后端获取医生信息失败:', e);
                    }
                }
                
                if (!dId) {
                    console.error('无法获取医生ID');
                    // 显示默认信息
                    document.getElementById('profileDId').value = '未获取到';
                    document.getElementById('profileName').value = '未获取到';
                    document.getElementById('profileSex').value = '未获取到';
                    document.getElementById('profileAge').value = '未获取到';
                    document.getElementById('profileTitle').value = '未获取到';
                    document.getElementById('profileMajor').value = '未获取到';
                    document.getElementById('profileInfo').value = '未获取到';
                    document.getElementById('profileDepName').value = '未获取到';
                    return;
                }
                
                console.log('使用医生ID查询个人信息:', dId);
                const response = await axios.get(`/doctor/info/${dId}`);
                console.log('医生信息查询响应:', response.data);
                
                if (response.data.code === 200) {
                    const doctor = response.data.data;
                    console.log('医生详细信息:', doctor);
                    
                    // 填充表单字段
                    console.log('开始填充表单字段...');
                    
                    const dIdValue = doctor.did || doctor.dId || '';
                    const dNameValue = doctor.dname || doctor.dName || '';
                    const dSexValue = doctor.dsex || doctor.dSex || '';
                    const dAgeValue = doctor.dage || doctor.dAge || '';
                    const dTitleValue = doctor.dtitle || doctor.dTitle || '';
                    const dMajorValue = doctor.dmajor || doctor.dMajor || '';
                    const dInfoValue = doctor.dinfo || doctor.dInfo || '';
                    
                    console.log('字段值:', {
                        dId: dIdValue,
                        dName: dNameValue,
                        dSex: dSexValue,
                        dAge: dAgeValue,
                        dTitle: dTitleValue,
                        dMajor: dMajorValue,
                        dInfo: dInfoValue
                    });
                    
                    document.getElementById('profileDId').value = dIdValue;
                    document.getElementById('profileName').value = dNameValue;
                    document.getElementById('profileSex').value = dSexValue;
                    document.getElementById('profileAge').value = dAgeValue;
                    document.getElementById('profileTitle').value = dTitleValue;
                    document.getElementById('profileMajor').value = dMajorValue;
                    document.getElementById('profileInfo').value = dInfoValue;
                    
                    console.log('个人信息字段填充完成');
                    
                    // 获取科室名称
                    if (doctor.depId) {
                        console.log('获取科室信息，科室ID:', doctor.depId);
                        try {
                            const depResponse = await axios.get(`/department/Info/${doctor.depId}`);
                            console.log('科室信息响应:', depResponse.data);
                            if (depResponse.data.code === 200) {
                                const depName = depResponse.data.data.depName || `科室${doctor.depId}`;
                                document.getElementById('profileDepName').value = depName;
                                console.log('科室名称设置成功:', depName);
                            } else {
                                document.getElementById('profileDepName').value = `科室${doctor.depId}`;
                            }
                        } catch (e) {
                            console.error('获取科室信息失败:', e);
                            document.getElementById('profileDepName').value = `科室${doctor.depId}`;
                        }
                    } else {
                        document.getElementById('profileDepName').value = '未分配科室';
                    }
                    
                    // 加载工作统计
                    loadWorkStatistics();
                    console.log('个人信息加载完成');
                } else {
                    console.error('获取医生信息失败:', response.data.msg);
                    // 显示错误信息
                    document.getElementById('profileDId').value = '获取失败';
                    document.getElementById('profileName').value = '获取失败';
                    document.getElementById('profileSex').value = '获取失败';
                    document.getElementById('profileAge').value = '获取失败';
                    document.getElementById('profileTitle').value = '获取失败';
                    document.getElementById('profileMajor').value = '获取失败';
                    document.getElementById('profileInfo').value = '获取失败';
                    document.getElementById('profileDepName').value = '获取失败';
                }
            } catch (error) {
                console.error('加载个人信息失败:', error);
                // 显示错误信息
                document.getElementById('profileDId').value = '加载失败';
                document.getElementById('profileName').value = '加载失败';
                document.getElementById('profileSex').value = '加载失败';
                document.getElementById('profileAge').value = '加载失败';
                document.getElementById('profileTitle').value = '加载失败';
                document.getElementById('profileMajor').value = '加载失败';
                document.getElementById('profileInfo').value = '加载失败';
                document.getElementById('profileDepName').value = '加载失败';
            }
        }

        // 加载工作统计
        async function loadWorkStatistics() {
            try {
                // 模拟工作统计数据（实际应用中应该从后端获取）
                document.getElementById('monthlyPatients').textContent = '12';
                document.getElementById('monthlyRecords').textContent = '8';
                document.getElementById('satisfaction').textContent = '98%';
            } catch (error) {
                console.error('加载工作统计失败:', error);
            }
        }



        // 显示新建病历模态框
        function showAddRecordModal(reservationId) {
            try {
                if (reservationId) {
                    currentDiagnosisReservationId = reservationId;
                }
                new bootstrap.Modal(document.getElementById('addRecordModal')).show();
                try {
                    let tip = '';
                    if (Array.isArray(latestReservationsForView) && latestReservationsForView.length) {
                        const found = latestReservationsForView.find(x => (x?.rv?.rId || x?.rv?.rid) == (reservationId || currentDiagnosisReservationId));
                        if (found) {
                            tip = (found.rv?.pname) || (found.rv?.pName) || '';
                            if (!tip) {
                                const pid = found.rv?.pId || found.rv?.pid || found.rv?.PId || found.rv?.PID;
                                if (pid) {
                                    // 尝试从缓存患者名
                                    tip = (found.patient?.pName) || (found.patient?.pname) || '';
                                }
                            }
                        }
                    }
                    const tipDiv = document.getElementById('recordPatientInfo');
                    if (tipDiv) tipDiv.textContent = tip ? `患者：${tip}` : '';
                } catch {}
            } catch (e) {
                console.error('显示病历弹窗失败:', e);
            }
        }

        // 添加病历
        async function addRecord() {
            try {
                const form = document.getElementById('addRecordForm');
                if (!form) { alert('找不到病历表单'); return; }
                const formData = new FormData(form);
                const payload = Object.fromEntries(formData);
                const rId = parseInt(currentDiagnosisReservationId || '');
                if (!rId || isNaN(rId)) { alert('缺少预约ID'); return; }
                const body = { rId, result: payload.result, info: payload.info, advice: payload.advice };

                const response = await axios.post('/medical/record', body);
                if (response && response.data && response.data.code === 200) {
                    // 取提示中的患者名
                    let patientName = document.getElementById('recordPatientInfo')?.textContent?.replace(/^患者：/, '') || '';
                    if (!patientName && Array.isArray(latestReservationsForView)) {
                        const match = latestReservationsForView.find(x => (x?.rv?.rId || x?.rv?.rid) == rId);
                        patientName = (match?.rv?.pname) || (match?.rv?.pName) || '';
                    }
                    alert(`病历保存成功！\n预约ID：${rId}${patientName ? `\n患者：${patientName}` : ''}`);
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addRecordModal'));
                    if (modal) modal.hide();
                    form.reset();
                    try { await loadMedicalRecords(); } catch {}
                } else {
                    alert('保存失败：' + (response?.data?.msg || '未知错误'));
                }
            } catch (error) {
                console.error('保存病历失败:', error);
                alert('保存病历失败，请检查网络连接');
            }
        }

        // 查看患者详情（与后端接口连接）
        async function viewPatient(patientId) {
            try {
                if (!patientId || patientId <= 0) {
                    alert('无效的患者ID');
                    return;
                }

                // 获取患者信息
                let pRes;
                try { pRes = await axios.get(`/patient/info/${patientId}`); } catch (e) { pRes = null; }
                const pData = pRes && pRes.data && pRes.data.code === 200 ? (pRes.data.data || {}) : {};

                // 从缓存的预约中找与该患者相关的一条，补齐预约时间/备注
                let related = null;
                if (Array.isArray(latestReservationsForView) && latestReservationsForView.length) {
                    related = latestReservationsForView.find(x => {
                        const pid = x?.rv?.pId || x?.rv?.pid || x?.rv?.PId || x?.rv?.PID;
                        return pid == patientId;
                    }) || null;
                }

                // 格式化预约时间
                let apptTimeStr = '-';
                if (related && related.schedule) {
                    try {
                        const dv = related.schedule.date;
                        let ymd = '-';
                        if (dv) {
                            if (typeof dv === 'string') ymd = dv.split('T')[0];
                            else { const d = new Date(dv); if (!isNaN(d)) ymd = d.toISOString().split('T')[0]; }
                        }
                        const time = related.schedule.time || '';
                        apptTimeStr = `${ymd} ${time}`.trim();
                    } catch {}
                }

                // 计算年龄：优先使用 pAge；若没有，尝试从身份证号推算
                const name = pData.pName || pData.pname || '-';
                const phone = pData.pPhone || pData.pphone || '-';
                let age = pData.pAge || pData.page || '';
                if (!age) {
                    const cardId = pData.pCardId || pData.pcardId || pData.cardId || '';
                    if (cardId && cardId.length >= 14) {
                        try {
                            const y = parseInt(cardId.substring(6, 10));
                            const m = parseInt(cardId.substring(10, 12));
                            const d = parseInt(cardId.substring(12, 14));
                            if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
                                const dob = new Date(y, m - 1, d);
                                const today = new Date();
                                let a = today.getFullYear() - dob.getFullYear();
                                const mo = today.getMonth() - dob.getMonth();
                                if (mo < 0 || (mo === 0 && today.getDate() < dob.getDate())) a--;
                                if (a >= 0 && a < 150) age = a;
                            }
                        } catch {}
                    }
                }
                let note = related?.rv?.rInfo || related?.rv?.rinfo || '';
                // 若未匹配到备注，兜底从患者所有预约中取最近一条有备注的
                if (!note) {
                    try {
                        const rRes = await axios.get(`/reservation/select/${patientId}`);
                        if (rRes.data && rRes.data.code === 200 && Array.isArray(rRes.data.data)) {
                            const withNote = rRes.data.data.find(x => (x.rInfo || x.rinfo));
                            if (withNote) note = withNote.rInfo || withNote.rinfo;
                        }
                    } catch {}
                }

            const content = `
                <div class="patient-info">
                    <h6>患者基本信息</h6>
                        <p><strong>姓名：</strong>${name}</p>
                        <p><strong>年龄：</strong>${(age || age === 0) ? age + '岁' : '-'}</p>
                        <p><strong>联系电话：</strong>${phone}</p>
                        <p><strong>预约时间：</strong>${apptTimeStr}</p>
                        <p><strong>预约备注：</strong>${note || '-'}</p>
                </div>
            `;
            document.getElementById('patientDetailContent').innerHTML = content;
            new bootstrap.Modal(document.getElementById('patientDetailModal')).show();
            } catch (error) {
                console.error('查看患者详情失败:', error);
                alert('查看患者详情失败，请稍后重试');
            }
        }

        // 开始诊断
        function startDiagnosis(reservationId) {
            if (reservationId) currentDiagnosisReservationId = reservationId;
            showAddRecordModal(reservationId);
        }

        // 查看病历
        function viewRecord(recordId) {
            alert('查看病历功能待实现');
        }

        // 编辑个人信息
        function editProfile() {
            alert('编辑个人信息功能待实现');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                window.location.href = '/login';
            }
        }

        // 住院审核相关变量
        let currentApplicationId = null;
        let allApplications = [];

        // 加载住院申请列表
        async function loadHospitalizationApplications() {
            try {
                const tbody = document.getElementById('hospitalizationApplicationsTable');
                showLoadingState('hospitalizationApplicationsTable', '正在加载住院申请...', 8);

                // 获取当前医生的科室ID
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                let dId = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                let depId = null;

                if (dId) {
                    try {
                        const doctorResponse = await axios.get(`/doctor/info/${dId}`);
                        if (doctorResponse.data.code === 200) {
                            depId = doctorResponse.data.data.depId;
                        }
                    } catch (e) {
                        console.error('获取医生科室信息失败:', e);
                    }
                }

                // 获取申请列表（按当前医生ID）
                let response;
                const statusFilter = document.getElementById('approvalStatusFilter')?.value || '';
                
                try {
                    if (dId && statusFilter !== '') {
                        // 优先按医生+状态查询
                        response = await axios.get(`/admission/doctor/${dId}/state/${statusFilter}`);
                    } else if (dId) {
                        // 仅按医生查询
                        response = await axios.get(`/admission/doctor/${dId}`);
                    }
                } catch (_) {
                    // 忽略，回退到旧逻辑
                }
                if (!response) {
                    if (depId && statusFilter !== '') {
                        response = await axios.get(`/admission/department/${depId}/state/${statusFilter}`);
                    } else if (statusFilter !== '') {
                        if (statusFilter === '0') {
                            response = await axios.get('/admission/pending');
                        } else {
                            response = await axios.get('/admission/all');
                            if (response.data.code === 200) {
                                const allApps = response.data.data || [];
                                response.data.data = allApps.filter(app => String(app.aState) === statusFilter);
                            }
                        }
                    } else {
                        response = await axios.get('/admission/all');
                    }
                }

                if (response.data.code === 200) {
                    allApplications = response.data.data || [];
                    
                    // 获取患者和科室信息
                    const [patientResponse, departmentResponse] = await Promise.all([
                        axios.get('/patient/query').catch(error => {
                            console.error('获取患者信息失败:', error);
                            return { data: { code: 500, data: [] } };
                        }),
                        axios.get('/department/query').catch(error => {
                            console.error('获取科室信息失败:', error);
                            return { data: { code: 500, data: [] } };
                        })
                    ]);

                    const patients = patientResponse.data.code === 200 ? patientResponse.data.data : [];
                    const departments = departmentResponse.data.code === 200 ? departmentResponse.data.data : [];

                    console.log('获取到的患者数据:', patients);
                    console.log('获取到的科室数据:', departments);

                    const patientMap = new Map();
                    patients.forEach(p => {
                        const patientId = p.pId || p.pid || p.PId || p.PID;
                        if (patientId) {
                            patientMap.set(patientId, p);
                        }
                    });

                    const departmentMap = new Map();
                    departments.forEach(d => {
                        const depId = d.depId || d.depid || d.DepId;
                        const depName = d.depName || d.depname || d.DepName || `科室${depId}`;
                        if (depId) {
                            departmentMap.set(depId, depName);
                        }
                    });

                    // 更新统计数据
                    updateApplicationStatistics(allApplications);

                    // 渲染表格
                    tbody.innerHTML = '';
                    if (allApplications.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无住院申请</td></tr>';
                        return;
                    }

                    allApplications.forEach(app => {
                        console.log('处理住院申请:', app);
                        
                        // 获取患者信息，支持多种字段名格式
                        const patientId = app.pId || app.pid || app.PId || app.PID;
                        const patient = patientMap.get(patientId) || {};
                        const patientName = patient.pName || patient.pname || patient.PName || patient.name || '未知患者';
                        
                        // 获取科室信息，支持多种字段名格式
                        const depId = app.depId || app.depid || app.DepId;
                        const depName = departmentMap.get(depId) || `科室${depId}` || '未知科室';
                        
                        // 获取申请状态和紧急程度
                        const stateValue = app.aState !== undefined ? app.aState : (app.astate !== undefined ? app.astate : app.AState);
                        const statusText = getAdmissionStatusText(stateValue);
                        const statusClass = getAdmissionStatusClass(stateValue);
                        const urgencyValue = app.aUrgency !== undefined ? app.aUrgency : (app.aurgency !== undefined ? app.aurgency : app.AUrgency);
                        const urgencyText = getUrgencyText(urgencyValue);
                        const urgencyClass = getUrgencyClass(urgencyValue);
                        
                        // 格式化申请时间（更强健的字段与格式兼容）
                        let applyTime = '-';
                        try {
                            const pick = (obj, keys) => { for (const k of keys) { if (obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k]; } };
                            let timeValue = pick(app, [
                                'aApplyTime','aapplytime','AApplyTime','AAPPLYTIME','a_apply_time',
                                'applyTime','ApplyTime','createTime','CreateTime','ctime','gmtCreate','gmtCreated',
                                'aTime','atime','a_time'
                            ]);
                            if (!timeValue) {
                                const entries = Object.entries(app || {}).filter(([k,v]) => /time/i.test(k) && v);
                                if (entries.length) timeValue = entries[0][1];
                            }
                            const parseTime = (val) => {
                                if (!val) return null;
                                try {
                                    if (Array.isArray(val)) return new Date(val[0], (val[1]||1)-1, val[2]||1, val[3]||0, val[4]||0, val[5]||0);
                                    if (typeof val === 'object' && (val.year||val.monthValue||val.dayOfMonth)) {
                                        const y=val.year||val.y, m=(val.monthValue||val.month||1), d0=(val.dayOfMonth||val.day||1);
                                        return new Date(y, m-1, d0, val.hour||0, val.minute||0, val.second||0);
                                    }
                                    if (typeof val === 'number' || (/^\d+$/.test(String(val)))) return new Date(Number(val));
                                    if (typeof val === 'string') {
                                        let s = val.trim();
                                        if (/^\d{4}[./-]\d{1,2}[./-]\d{1,2}/.test(s) || /T/.test(s) || /:\d{2}/.test(s)) {
                                            let d = new Date(s);
                                            if (isNaN(d)) d = new Date(s.replace(' ', 'T'));
                                            if (isNaN(d) && /[./]/.test(s)) d = new Date(s.replace(/[.]/g,'-'));
                                            if (!isNaN(d)) return d;
                                        }
                                    }
                                } catch {}
                                return null;
                            };
                            const d = parseTime(timeValue);
                            if (d && !isNaN(d.getTime())) {
                                applyTime = d.toLocaleString('zh-CN', { year:'numeric', month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' });
                            }
                        } catch (e) { /* 忽略，保持 '-' */ }

                        // 获取申请编号和病房类型
                        const applicationNumber = app.aNumber || app.anumber || `ADM${app.aId || ''}` || '-';
                        const wardType = app.wType || app.wtype || app.WType || '-';

                        const row = `
                            <tr>
                                <td>${applicationNumber}</td>
                                <td>${patientName}</td>
                                <td>${depName}</td>
                                <td>${wardType}</td>
                                <td><span class="badge ${urgencyClass}">${urgencyText}</span></td>
                                <td>${applyTime}</td>
                                <td><span class="badge ${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewApplicationDetail(${app.aId || app.aid || 0})">查看</button>
                                    ${(app.aState === 0 || app.astate === 0) ? `
                                        <button class="btn btn-sm btn-success" onclick="quickApprove(${app.aId || app.aid || 0})">批准</button>
                                        <button class="btn btn-sm btn-danger" onclick="quickReject(${app.aId || app.aid || 0})">拒绝</button>
                                    ` : ''}
                                </td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                    });
                } else {
                    showErrorState('hospitalizationApplicationsTable', '加载失败：' + (response.data.msg || '未知错误'), 8);
                }
            } catch (error) {
                console.error('加载住院申请失败:', error);
                showErrorState('hospitalizationApplicationsTable', '加载失败，请检查网络连接', 8);
            }
        }

        // 更新申请统计数据
        function updateApplicationStatistics(applications) {
            const pending = applications.filter(app => app.aState === 0).length;
            const approved = applications.filter(app => app.aState === 1).length;
            const rejected = applications.filter(app => app.aState === 2).length;
            const urgent = applications.filter(app => app.aUrgency === 3).length;

            document.getElementById('pendingApplications').textContent = pending;
            document.getElementById('approvedApplications').textContent = approved;
            document.getElementById('rejectedApplications').textContent = rejected;
            document.getElementById('urgentApplications').textContent = urgent;
        }

        // 获取申请状态文本
        function getAdmissionStatusText(status) {
            const statusMap = {
                0: '待审批',
                1: '已批准',
                2: '已拒绝',
                3: '已入院',
                4: '已取消'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取申请状态样式
        function getAdmissionStatusClass(status) {
            const classMap = {
                0: 'bg-warning',
                1: 'bg-success',
                2: 'bg-danger',
                3: 'bg-info',
                4: 'bg-secondary'
            };
            return classMap[status] || 'bg-secondary';
        }

        // 获取紧急程度文本
        function getUrgencyText(urgency) {
            const urgencyMap = {
                1: '普通',
                2: '紧急',
                3: '危重'
            };
            return urgencyMap[urgency] || '普通';
        }

        // 获取紧急程度样式
        function getUrgencyClass(urgency) {
            const classMap = {
                1: 'bg-secondary',
                2: 'bg-warning',
                3: 'bg-danger'
            };
            return classMap[urgency] || 'bg-secondary';
        }

        // 查看申请详情（字段兼容更强 + 时间/字典映射健壮化）
        async function viewApplicationDetail(aId) {
            try {
                currentApplicationId = aId;

                // 1) 获取详情，失败尝试备用路径
                let resp = null;
                try { resp = await axios.get(`/admission/info/${aId}`); } catch (_) {}
                if (!resp || resp.data?.code !== 200) {
                    try { resp = await axios.get(`/admission/detail/${aId}`); } catch (_) {}
                }
                if (!resp || resp.data?.code !== 200 || !resp.data?.data) {
                    alert('获取申请详情失败');
                    return;
                }
                const app = resp.data.data || {};

                const pick = (obj, keys, def='-') => { for (const k of keys) { if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k]; } return def; };
                const fmtTime = (v) => {
                    if (!v) return '-';
                    try {
                        if (Array.isArray(v)) { const d = new Date(v[0], (v[1]||1)-1, v[2]||1, v[3]||0, v[4]||0, v[5]||0); return isNaN(d)?'-':d.toLocaleString(); }
                        if (typeof v === 'object' && v.year && (v.monthValue||v.month) && (v.dayOfMonth||v.day)) {
                            const d = new Date(v.year, (v.monthValue||v.month)-1, (v.dayOfMonth||v.day), v.hour||0, v.minute||0, v.second||0); return isNaN(d)?'-':d.toLocaleString();
                        }
                        const d = new Date(v); return isNaN(d)?'-':d.toLocaleString();
                    } catch { return '-'; }
                };

                // 2) 关键信息
                const appNumber = pick(app, ['aNumber','anumber','number','applicationNumber','aId','aid'], '-');
                const applyTime = fmtTime(pick(app, ['aApplyTime','aapplytime','AApplyTime','AAPPLYTIME','applyTime','createTime','a_apply_time'], null));
                const stateVal = Number(pick(app, ['aState','astate','AState','state'], 0));
                const urgencyVal = Number(pick(app, ['aUrgency','aurgency','Aurgency','AURGENCY'], 1));
                const wType = pick(app, ['wType','wtype','wardType'], '-');
                const reason = pick(app, ['aReason','areason','reason','aDescription','adescription'], '-');
                const diagnosis = pick(app, ['aDiagnosis','adiagnosis','diagnosis'], '-');
                const remark = pick(app, ['aRemark','aremark','remark'], '-');
                const rejectReason = pick(app, ['aRejectReason','rejectReason'], null);
                const approveTime = fmtTime(pick(app, ['aApproveTime','approveTime'], null));

                // 3) 科室/患者/医生
                const depId = pick(app, ['depId','depid','DepId','departmentId'], null);
                let depName = pick(app, ['depName','depname','departmentName'], null);
                if (!depName && depId && depId !== '-') {
                    try { const depR = await axios.get(`/department/Info/${depId}`); if (depR.data?.code === 200) depName = pick(depR.data.data, ['depName','depname','name'], `科室${depId}`); } catch {}
                }
                if (!depName) depName = depId ? `科室${depId}` : '-';

                const pId = pick(app, ['pId','pid','patientId'], null);
                let patient = {};
                if (pId && pId !== '-') { try { const pR = await axios.get(`/patient/info/${pId}`); if (pR.data?.code === 200) patient = pR.data.data || {}; } catch {} }
                const pName = pick(patient, ['pName','pname','name'], '-');
                const pPhone = pick(patient, ['pPhone','pphone','phone'], '-');

                const dId = pick(app, ['dId','did','doctorId'], null);
                let doc = {};
                if (dId && dId !== '-') { try { const dR = await axios.get(`/doctor/info/${dId}`); if (dR.data?.code === 200) doc = dR.data.data || {}; } catch {} }
                const dName = pick(doc, ['dName','dname','name'], '未指定');

                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>申请信息</h6>
                            <p><strong>申请编号：</strong>${appNumber}</p>
                            <p><strong>申请时间：</strong>${applyTime}</p>
                            <p><strong>申请状态：</strong><span class="badge ${getAdmissionStatusClass(stateVal)}">${getAdmissionStatusText(stateVal)}</span></p>
                            <p><strong>紧急程度：</strong><span class="badge ${getUrgencyClass(urgencyVal)}">${getUrgencyText(urgencyVal)}</span></p>
                            <p><strong>病房类型：</strong>${wType}</p>
                        </div>
                        <div class="col-md-6">
                            <h6>患者信息</h6>
                            <p><strong>患者姓名：</strong>${pName}</p>
                            <p><strong>联系电话：</strong>${pPhone}</p>
                            <p><strong>申请科室：</strong>${depName}</p>
                            <p><strong>申请医生：</strong>${dName}</p>
                        </div>
                    </div>
                    <hr>
                    <div class="mb-3">
                        <h6>住院原因</h6>
                        <p class="text-muted">${reason}</p>
                    </div>
                    <div class="mb-3">
                        <h6>初步诊断</h6>
                        <p class="text-muted">${diagnosis}</p>
                    </div>
                    <div class="mb-3">
                        <h6>备注信息</h6>
                        <p class="text-muted">${remark}</p>
                    </div>
                    ${stateVal === 2 && rejectReason ? `
                    <div class="mb-3">
                        <h6>拒绝原因</h6>
                        <p class="text-danger">${rejectReason}</p>
                    </div>` : ''}
                    ${approveTime && approveTime !== '-' ? `
                    <div class="mb-3">
                        <h6>审批时间</h6>
                        <p class="text-muted">${approveTime}</p>
                    </div>` : ''}
                `;

                document.getElementById('admissionDetailContent').innerHTML = content;

                // 根据状态显示/隐藏按钮
                const approveBtn = document.getElementById('approveBtn');
                const rejectBtn = document.getElementById('rejectBtn');
                if (stateVal === 0) { approveBtn.style.display = 'inline-block'; rejectBtn.style.display = 'inline-block'; }
                else { approveBtn.style.display = 'none'; rejectBtn.style.display = 'none'; }

                new bootstrap.Modal(document.getElementById('admissionDetailModal')).show();
            } catch (error) {
                console.error('查看申请详情失败:', error);
                alert('查看申请详情失败，请稍后重试');
            }
        }

        // 快速批准申请
        async function quickApprove(aId) {
            if (confirm('确定要批准这个住院申请吗？')) {
                await approveApplicationById(aId);
            }
        }

        // 快速拒绝申请
        async function quickReject(aId) {
            const reason = prompt('请输入拒绝原因：');
            if (reason && reason.trim()) {
                await rejectApplicationById(aId, reason.trim());
            }
        }

        // 批准申请
        async function approveApplication() {
            if (currentApplicationId) {
                await approveApplicationById(currentApplicationId);
            }
        }

        // 批准申请的具体实现
        async function approveApplicationById(aId) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approveDoctor = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                
                if (!approveDoctor) {
                    alert('无法获取医生ID，无法进行审批');
                    return;
                }

                const response = await axios.post(`/admission/approve/${aId}`, null, {
                    params: { approveDoctor: approveDoctor }
                });
                
                if (response.data.code === 200) {
                    alert('申请已批准！');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('admissionDetailModal'));
                    if (modal) modal.hide();
                    // 刷新列表
                    loadHospitalizationApplications();
                } else {
                    alert('批准失败：' + (response.data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('批准申请失败:', error);
                alert('批准失败，请检查网络连接');
            }
        }

        // 显示拒绝模态框
        function showRejectModal() {
            document.getElementById('rejectReason').value = '';
            new bootstrap.Modal(document.getElementById('rejectModal')).show();
        }

        // 确认拒绝申请
        async function confirmRejectApplication() {
            const reason = document.getElementById('rejectReason').value.trim();
            if (!reason) {
                alert('请输入拒绝原因');
                return;
            }
            
            if (currentApplicationId) {
                await rejectApplicationById(currentApplicationId, reason);
            }
        }

        // 拒绝申请的具体实现
        async function rejectApplicationById(aId, reason) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approveDoctor = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                
                if (!approveDoctor) {
                    alert('无法获取医生ID，无法进行审批');
                    return;
                }

                const response = await axios.post(`/admission/reject/${aId}`, null, {
                    params: { 
                        approveDoctor: approveDoctor,
                        rejectReason: reason
                    }
                });
                
                if (response.data.code === 200) {
                    alert('申请已拒绝！');
                    // 关闭所有模态框
                    const detailModal = bootstrap.Modal.getInstance(document.getElementById('admissionDetailModal'));
                    if (detailModal) detailModal.hide();
                    const rejectModal = bootstrap.Modal.getInstance(document.getElementById('rejectModal'));
                    if (rejectModal) rejectModal.hide();
                    // 刷新列表
                    loadHospitalizationApplications();
                } else {
                    alert('拒绝失败：' + (response.data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('拒绝申请失败:', error);
                alert('拒绝失败，请检查网络连接');
            }
        }

        // 购药审批模块
        function showDrugPurchaseApproval() {
            hideAllSections();
            document.getElementById('drugPurchaseApproval').style.display = 'block';
            updateActiveNav('drugPurchaseApproval');
            loadDrugPurchasePending();
        }

        async function loadDrugPurchasePending() {
            const tbody = document.getElementById('purchaseApprovalTable');
            if (!tbody) return;
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载中...</td></tr>';
            try {
                const [pendingRes, patientRes] = await Promise.all([
                    axios.get('/purchase/pending'),
                    axios.get('/patient/query').catch(_=>({data:{code:500,data:[]}}))
                ]);
                if (!(pendingRes.data && pendingRes.data.code === 200)) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const patients = (patientRes.data && patientRes.data.code===200) ? (patientRes.data.data||[]) : [];
                const pMap = new Map();
                patients.forEach(p=>{ const id=p.pId||p.pid||p.id; if(id) pMap.set(Number(id), p); });

                const list = pendingRes.data.data || [];
                if (!list.length) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无待审批申请</td></tr>';
                    return;
                }
                tbody.innerHTML = list.map(x=>{
                    const pid = Number(x.pId||x.pid);
                    const p = pMap.get(pid)||{};
                    const pname = p.pName||p.pname||'-';
                    const time = x.applyTime ? new Date(x.applyTime).toLocaleString() : '-';
                    const total = (Number(x.totalAmount)||0).toFixed(2);
                    const items = Array.isArray(x.items)? x.items.map(it => `${it.drugName}x${it.quantity}`).join('，') : '';
                    return `
                        <tr>
                            <td>PU${x.purchaseId}</td>
                            <td>${pname}</td>
                            <td>${time}</td>
                            <td>${total}</td>
                            <td><button class="btn btn-sm btn-outline-primary" onclick="alert('${items.replace(/'/g, "\\'")}')">查看</button></td>
                            <td>
                                <button class="btn btn-sm btn-success me-1" onclick="approvePurchase(${x.purchaseId}, true)">通过</button>
                                <button class="btn btn-sm btn-danger" onclick="approvePurchase(${x.purchaseId}, false)">拒绝</button>
                            </td>
                        </tr>`;
                }).join('');
            } catch (e) {
                console.error('加载购药审批列表失败', e);
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        async function approvePurchase(purchaseId, pass) {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const approverId = userInfo.dId || userInfo.did || userInfo.id || userInfo.uId;
                if (!approverId) { alert('无法获取医生ID'); return; }
                const body = { purchaseId, approverId, approverRole: 2, pass, remark: '' };
                const res = await axios.post('/purchase/approve', body);
                if (res.data && res.data.code === 200) {
                    alert('操作成功');
                    loadDrugPurchasePending();
                } else {
                    alert('操作失败：' + (res.data?.msg || '未知错误'));
                }
            } catch (e) {
                console.error('审批失败', e);
                alert('审批失败，请稍后重试');
            }
        }

        // 暴露函数到全局，确保内联 onclick 可调用
        window.viewPatient = viewPatient;
        window.startDiagnosis = startDiagnosis;
        window.addRecord = typeof addRecord === 'function' ? addRecord : undefined;
        window.showAddRecordModal = showAddRecordModal;
        window.viewApplicationDetail = viewApplicationDetail;
        window.quickApprove = quickApprove;
        window.quickReject = quickReject;
        window.approveApplication = approveApplication;
        window.showRejectModal = showRejectModal;
        window.confirmRejectApplication = confirmRejectApplication;
        // 新增：购药审批全局方法
        window.showDrugPurchaseApproval = showDrugPurchaseApproval;
        window.loadDrugPurchasePending = loadDrugPurchasePending;
        window.approvePurchase = approvePurchase;
    </script>
</body>
</html>
